package com.reformer.commons.utils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharSetUtil {
    /**
     * 解码 Unicode \\uXXXX
     *
     * @param str
     * @return
     */
    public static String decodeUnicode(String str) {
        StringBuffer sb = new StringBuffer();
        try {
            Charset set = Charset.forName("UTF-16");
            Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
            Matcher m = p.matcher(str);
            int start = 0;
            int start2 = 0;
            while (m.find(start)) {
                start2 = m.start();
                if (start2 > start) {
                    String seg = str.substring(start, start2);
                    sb.append(seg);
                }
                String code = m.group(1);
                int i = Integer.valueOf(code, 16);
                byte[] bb = new byte[4];
                bb[0] = (byte) ((i >> 8) & 0xFF);
                bb[1] = (byte) (i & 0xFF);
                ByteBuffer b = ByteBuffer.wrap(bb);
                sb.append(String.valueOf(set.decode(b)).trim());
                start = m.end();
            }
            start2 = str.length();
            if (start2 > start) {
                String seg = str.substring(start, start2);
                sb.append(seg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 对字符字符串中的中文编码
     *
     * @param url 要编码的字符串
     * @param enc 编码格式 UTF-8 GBK等
     * @return
     */
    public static String encode(String url, String enc) {
        try {
            Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
            // int count = 0;
            while (matcher.find()) {
                // System.out.println(matcher.group());
                String tmp = matcher.group();
                url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, enc));
            }
            // System.out.println(count);
            // url = java.net.URLEncoder.encode(url,"gbk");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return url;
    }

    public static void main(String[] args) {
        System.out.println(decodeUnicode("\\u5907abbbbbs\\u5906"));
    }
}
